package org.code.mallspringboot.controller;

import org.code.mallspringboot.dto.PmsBrandDto;
import org.code.mallspringboot.pojo.PmsBrand;
import org.code.mallspringboot.service.PmsBrandService;
import org.code.mallspringboot.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/brand")
public class PmsBrandController {


    @Autowired
    private PmsBrandService pmsBrandService;


    @GetMapping("/list")
    public CommonResult list(String keyword,
                             @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){

        List<PmsBrand> list = pmsBrandService.selectPage(keyword,pageNum, pageSize);
        int total = pmsBrandService.total(keyword);
        int totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        Map map = new HashMap();
        map.put("list",list);
        map.put("total",total);
        map.put("totalPage",totalPage);
        map.put("pageSize",pageSize);
        if (map.size() > 0){
            return CommonResult.success(map);
        }
        return CommonResult.failed("查询+分页失败!");
    }

    //编辑回显
    @GetMapping("/{id}")
    public CommonResult getBrand(@PathVariable int id){
        PmsBrand brand = pmsBrandService.getBrand(id);
        if (brand != null){
            return CommonResult.success(brand);
        }
        return CommonResult.failed("回显失败");
    }

    //编辑提交
    @PostMapping("/update/{id}")
    public CommonResult updateBrand(@PathVariable int id, @RequestBody PmsBrandDto pmsBrandDto){

        pmsBrandDto.setId(id);
        if (pmsBrandService.update(pmsBrandDto) > 0){
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    //添加提交
    @PostMapping("/create")
    public CommonResult create(@RequestBody PmsBrandDto pmsBrandDto){
        if (pmsBrandService.add(pmsBrandDto) > 0){
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("添加失败");
    }

    //删除
    @GetMapping("/delete/{id}")
    public CommonResult delete(@PathVariable int id){
        if (pmsBrandService.delete(id) > 0){
            return CommonResult.success("删除成功");
        }
        return CommonResult.failed("删除失败!");
    }

    //批量操作
    @PostMapping("/update/showStatus")
    public CommonResult showStatus(int[] ids,int showStatus){
        boolean flag = false;
        for (int id : ids) {
            if (pmsBrandService.update_status(id,showStatus) > 0){
                flag = true;
            }else{
                flag = false;
            }
        }
        if (flag){
            return CommonResult.success("批量修改成功");
        }
        return CommonResult.failed("批量修改失败");
    }
}
